/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package da;

import Config.ConfigXML;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
import java.sql.Connection;

/**
 *
 * @author Hung.Scago
 */
public class MSSQLConnection extends BaseConnection{

    public MSSQLConnection(String host, String name, String passWord, String dataBase,int port) {
        MSSQLConnection.host = host;
        MSSQLConnection.name = name;
        MSSQLConnection.passWord = passWord;
        MSSQLConnection.dataBase = dataBase;
        MSSQLConnection.port = port;
    }

    public MSSQLConnection() {
        if(MSSQLConnection.host.equals("")){
            ConfigXML config = new ConfigXML();
            config.readXML();
            MSSQLConnection.host = config.getServerName();
            MSSQLConnection.name = config.getUserName();
            MSSQLConnection.passWord = config.getPassWord();
            MSSQLConnection.dataBase = config.getDataName();
            MSSQLConnection.port = Integer.parseInt(config.getPort());
        }
        
    }

    public MSSQLConnection(boolean isConfigSuccess) {
        ConfigXML config = new ConfigXML();
        config.readXML();
        MSSQLConnection.host = config.getServerName();
        MSSQLConnection.name = config.getUserName();
        MSSQLConnection.passWord = config.getPassWord();
        MSSQLConnection.dataBase = config.getDataName();
        MSSQLConnection.port = Integer.parseInt(config.getPort());
    }

    @Override
    public Connection getConnection() throws Exception {
        if(this.connect ==null){
            testDriver();
           // try{
                SQLServerDataSource ds = new SQLServerDataSource();
                ds.setServerName(MSSQLConnection.host);
                ds.setUser(MSSQLConnection.name);
                ds.setPassword(MSSQLConnection.passWord);
                ds.setPortNumber(MSSQLConnection.port);
                ds.setDatabaseName(MSSQLConnection.dataBase);

                this.connect = ds.getConnection();
                System.out.println("Connect database succeed");

            //}catch(java.sql.SQLException e){
               // throw new Exception("Can not connect to database");
//                JOptionPane.showMessageDialog(, "Can not connect to database");
            //}

        }
        return this.connect;
    }

    @Override
    public void testDriver() throws Exception {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        } catch (java.lang.ClassNotFoundException e) {
            throw new Exception("MSSQL JDBC Driver not found");
        }
    }


    

}
